package com.lenovo.smarttraffic.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.SpotInfoBean;
import com.lenovo.smarttraffic.ui.adapter.MyVpAdapter;
import com.lenovo.smarttraffic.ui.fragment.stage8.NewsFragment;
import com.lenovo.smarttraffic.util.CommonUtil;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

public class Item1Activity extends BaseActivity {

    public static List<SpotInfoBean.ROWSDETAILBean> spotList = new ArrayList<>();

    private List<Fragment> fragmentList = new ArrayList<>();

    public static String[] cates = {"所有", "推荐", "热点", "科技", "汽车资讯", "健康", "财经", "教育", "旅游", "军事", "实时路况", "文化", "二手车", "违章资讯", "娱乐", "体育", "视频", "游戏", "电影"};

    public static List<String> curr_cate = new ArrayList<>();
    public static List<String> other_cate = new ArrayList<>();


    @BindView(R.id.toolbar_main)
    Toolbar toolbar;

    @BindView(R.id.news_parent)
    LinearLayout news_parent;
    @BindView(R.id.tab_layout_list)
    TabLayout tabLayoutList;
    @BindView(R.id.header_layout)
    LinearLayout headerLayout;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.add_btn)
    ImageButton add_btn;

    private MyVpAdapter vpAdapter;


    @BindView(R.id.dingyue_parent)
    LinearLayout dingyue_parent;
    @BindView(R.id.ok_btn)
    Button ok_btn;
    @BindView(R.id.rvView1)
    RecyclerView rvView1;
    @BindView(R.id.rvView2)
    RecyclerView rvView2;

    public DingYueAdapter adapter1;
    public DingYueAdapter adapter2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //获取旅游信息
        HttpUtils.post("GetSpotInfo.do", new HttpUtils().add("UserName", MainActivity.userName),
                response -> spotList = new Gson().fromJson(response.toString(), SpotInfoBean.class).getROWS_DETAIL());

        InitView();
        InitData();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_list_tab;
    }

    private void InitView() {
        toolbar.setTitle(getString(R.string.item1));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        tabLayoutList.setupWithViewPager(viewPager);
        tabLayoutList.setTabMode(TabLayout.MODE_SCROLLABLE);
        headerLayout.setBackgroundColor(CommonUtil.getInstance().getColor());
    }

    private void InitData() {
        //默认分类
        if (curr_cate.isEmpty()) {
            curr_cate.addAll(Arrays.asList(cates).subList(1, 5));
        }

        other_cate.clear();
        other_cate.addAll(Arrays.asList(cates).subList(1, cates.length));
        other_cate.removeAll(curr_cate);
        for (int i = 0; i < other_cate.size(); i++) {
            if (curr_cate.contains(other_cate.get(i))) {
                other_cate.remove((other_cate.get(i)));
            }
        }

        fragmentList.clear();
        for (int i = 0; i < curr_cate.size(); i++) {
            fragmentList.add(new NewsFragment().setType(Arrays.asList(cates).indexOf(curr_cate.get(i))));
        }

        if (vpAdapter == null) {
            vpAdapter = new MyVpAdapter(getSupportFragmentManager(), fragmentList, curr_cate);
            viewPager.setAdapter(vpAdapter);
            viewPager.setOffscreenPageLimit(fragmentList.size());
        } else {
            vpAdapter.notifyDataSetChanged();
        }

        add_btn.setOnClickListener(v -> toggleView());
        ok_btn.setOnClickListener(v -> toggleView());
    }

    private void toggleView() {
        if (news_parent.getVisibility() == View.VISIBLE) {
            toolbar.setTitle("添加订阅");
            news_parent.setVisibility(View.GONE);
            dingyue_parent.setVisibility(View.VISIBLE);
            ok_btn.setVisibility(View.GONE);

            if (adapter1 == null) {
                adapter1 = new DingYueAdapter(this, 1);
                rvView1.setAdapter(adapter1);
                mItemHelper.attachToRecyclerView(rvView1);
            } else {
                adapter1.showAction = false;
                adapter1.canAdd = false;
                adapter1.notifyItemRangeChanged(0, adapter1.getItemCount(), 0);
            }

            if (adapter2 == null) {
                adapter2 = new DingYueAdapter(this, 2);
                rvView2.setAdapter(adapter2);
            } else {
                adapter2.showAction = false;
                adapter1.canAdd = false;
                adapter2.notifyItemRangeChanged(0, adapter2.getItemCount(), 0);
            }
        } else {
            toolbar.setTitle(getString(R.string.item1));
            news_parent.setVisibility(View.VISIBLE);
            dingyue_parent.setVisibility(View.GONE);

            InitData();
        }
    }

    private ItemTouchHelper mItemHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                        ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                final int swipeFlags = 0;
                return makeMovementFlags(dragFlags, swipeFlags);
            } else {
                final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                final int swipeFlags = 0;
                return makeMovementFlags(dragFlags, swipeFlags);
            }
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            //得到当拖拽的viewHolder的Position
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(curr_cate, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(curr_cate, i, i - 1);
                }
            }
            recyclerView.getAdapter().notifyItemMoved(fromPosition, toPosition);
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        }

        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            super.onSelectedChanged(viewHolder, actionState);
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
            }

            if (ok_btn.getVisibility() == View.GONE) {
                ok_btn.setVisibility(View.VISIBLE);

                adapter1.showAction = true;
                adapter2.showAction = true;
                adapter1.notifyItemRangeChanged(0, adapter1.getItemCount(), 0);
                adapter2.notifyItemRangeChanged(0, adapter2.getItemCount(), 0);
            }
        }

        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            viewHolder.itemView.setBackgroundColor(0);
            adapter1.canAdd = true;
            adapter2.canAdd = true;
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return true;
        }
    });

    @Override
    public void onBackPressedSupport() {
        if (dingyue_parent.getVisibility() == View.VISIBLE) {
            toggleView();
        } else super.onBackPressedSupport();
    }

    @Override
    protected void onResume() {
        super.onResume();
        headerLayout.setBackgroundColor(CommonUtil.getInstance().getColor());
    }

}

class DingYueAdapter extends RecyclerView.Adapter<DingYueAdapter.ViewHolder> {

    private Item1Activity item1Activity;

    private List<String> data;
    private int type;

    boolean showAction = false, canAdd = false;

    public DingYueAdapter(Item1Activity item1Activity, int type) {
        this.item1Activity = item1Activity;
        this.type = type;

        if (type == 1) {
            data = Item1Activity.curr_cate;
        } else {
            data = Item1Activity.other_cate;
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_dingyue, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.title.setText(data.get(position));
        holder.icon.setBackgroundResource(type == 1 ? R.mipmap.plus : R.mipmap.add2);
        holder.icon.setVisibility(showAction ? View.VISIBLE : View.GONE);

        holder.itemView.setOnClickListener(v -> {
            try {
                if (showAction && canAdd) {
                    if (type == 1) {
                        if (getItemCount() < 2) {
                            ToastUtils.showToast(InitApp.getContext(), "至少选择一个订阅");
                            return;
                        }
                        Item1Activity.other_cate.add(data.get(position));
                    } else {
                        Item1Activity.curr_cate.add(data.get(position));
                        item1Activity.adapter1.notifyItemInserted(item1Activity.adapter2.getItemCount() - 1);
                    }
                    data.remove(position);
                    notifyDataSetChanged();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView title;
        View icon;

        public ViewHolder(View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.title);
            icon = itemView.findViewById(R.id.icon);
        }
    }
}
